import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lib_uikit/lib_uikit.dart';
import 'package:lib_uikit/widgets/dropdown/gt_dropdown_top_popup_widget_v3.dart';
import 'package:lib_uikit/widgets/gt_dropdown_v3.dart';

class GTDropdownTopPopupV3 extends StatefulWidget {
  //目标控件
  final Widget child;
  final List<GTDropDownContentModalV3>? list;
  final ValueChanged<GTDropDownContentModalV3>? onItemClicked;
  final String? selectTitle;
  final ValueChanged<bool>? onDropdownPressed;
  final double? topPopupMaxPercentHeight;
  final bool? showInput;
  final VoidCallback? onPressed;
  final String text;
  final Color? textColor;
  final String? tag;

  const GTDropdownTopPopupV3({
    super.key,
    required this.child,
    this.list,
    this.onItemClicked,
    this.selectTitle,
    this.onDropdownPressed,
    this.topPopupMaxPercentHeight,
    this.showInput,
    this.onPressed,
    this.text = "",
    this.textColor,
    this.tag,
  });

  @override
  State<StatefulWidget> createState() => _DropdownTopStateV3();
}

class _DropdownTopStateV3 extends State<GTDropdownTopPopupV3> {
  bool popupIsShowing = false;
  double bottomY = 0;

  @override
  Widget build(BuildContext context) {
    return Builder(builder: (context) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        RenderBox box = context.findRenderObject() as RenderBox;
        Offset position = box.localToGlobal(Offset.zero);
        Size size = box.size;
        bottomY = position.dy + size.height;
      });
      return GestureDetector(
        onTap: () {
          widget.onPressed?.call();
          if (popupIsShowing) {
            popupIsShowing = false;
            SmartDialog.dismiss(tag: widget.tag);
            return;
          }
          widget.onDropdownPressed?.call(true);
          popupIsShowing = true;
          SmartDialog.showAttach(
            maskColor: GTColorsV3.bg3.color,
            targetContext: context,
            tag: widget.tag,
            alignment: Alignment.bottomCenter,
            animationType: SmartAnimationType.scale,
            useAnimation: false,
            maskIgnoreArea: Rect.fromLTRB(0, bottomY < 0 ? 0 : bottomY, 0, 0),
            onDismiss: () {
              widget.onDropdownPressed?.call(false);
              popupIsShowing = false;
            },
            builder: (_) {
              return GTDropdownTopPopupWidgetV3(
                  showInput: widget.showInput,
                  list: widget.list,
                  selectTitle: widget.selectTitle,
                  text: widget.text,
                  textColor: widget.textColor,
                  tag: widget.tag,
                  topPopupMaxPercentHeight: widget.topPopupMaxPercentHeight,
                  onItemClicked: (bean) {
                    widget.onItemClicked?.call(bean);
                  });
            },
          );
        },
        child: widget.child,
      );
    });
  }
}
